package phototransfer.model.udp;

import android.util.Log;
import java.io.IOException;
import java.net.DatagramPacket;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

public class BroadcastReceiver {
   public static final String TAG = "BroadcastSender";
   private final byte[] mBuffer = new byte[256];
   private ScheduledExecutorService scheduledExecutorService;
   private UdpConnection mUdpConnection;
   private Set<String> mServerAddressSet = new TreeSet();
   private static BroadcastReceiver sInstance;

   public static BroadcastReceiver getInstance() {
      Class var0 = BroadcastReceiver.class;
      synchronized(BroadcastReceiver.class) {
         if (null == sInstance) {
            Class var1 = BroadcastReceiver.class;
            synchronized(BroadcastReceiver.class) {
               sInstance = new BroadcastReceiver();
            }
         }
      }

      return sInstance;
   }

   public boolean startRecvHeartBeat(int boardcastPort) {
      if (null != this.scheduledExecutorService) {
         return true;
      } else {
         this.mUdpConnection = new UdpConnection();
         this.mUdpConnection.start(boardcastPort);
         this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
         this.scheduledExecutorService.execute(new Runnable() {
            public void run() {
               try {
                  DatagramPacket datagramPacket = BroadcastReceiver.this.mUdpConnection.recv(BroadcastReceiver.this.mBuffer, BroadcastReceiver.this.mBuffer.length);
                  String address = datagramPacket.getAddress().getHostAddress();
                  if (!BroadcastReceiver.this.mServerAddressSet.contains(address)) {
                     BroadcastReceiver.this.mServerAddressSet.add(address);
                     Log.d("BroadcastSender", address + "is on line");
                  }
               } catch (IOException var3) {
                  var3.printStackTrace();
                  Log.e("BroadcastSender", "startHeartBeat: ", var3);
               }

            }
         });
         return true;
      }
   }

   public String[] stopRecvHeartBeat() {
      if (null != this.mUdpConnection) {
         this.mUdpConnection.close();
         this.mUdpConnection = null;
      }

      if (null != this.scheduledExecutorService) {
         this.scheduledExecutorService.shutdownNow();
         this.scheduledExecutorService = null;
      }

      String[] addressArr = new String[this.mServerAddressSet.size()];
      this.mServerAddressSet.toArray(addressArr);
      return addressArr;
   }
}
